package rss;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class RssReader {
	public RssReader(String site){
		this.site=site;
	}
	
	/**
	 * 
	 * @return ArrayList of sites in specified rss feed
	 */
	public ArrayList<Rss> getRssContent(){
		ArrayList<Rss> linksInRss=new ArrayList<Rss>();
		
		try {
			URL url=new URL(site);
			InputStream rssStream=url.openStream();
			
			Document document=this.createDocumentObjectFromInputStream(rssStream);
			
			XPath xpath=XPathFactory.newInstance().newXPath();
			int itemsLength=Integer.parseInt(xpath.evaluate("count(/rss/channel/item)",document));
			
			for(int i=1;i<itemsLength;i++){
				String title=xpath.evaluate("/rss/channel/item["+i+"]/title", document);
				String link=xpath.evaluate("/rss/channel/item["+i+"]/guid", document);
				linksInRss.add(new Rss(title,link));
			}
			
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch(IOException ex){
			ex.printStackTrace();
		} catch(SAXException ex){
			ex.printStackTrace();
		} catch(ParserConfigurationException ex){
			ex.printStackTrace();
		}catch(XPathExpressionException e){
			e.printStackTrace();
		}
		
		return linksInRss;
	}

	/**
	 * 
	 * @param stream input stream of rss feed
	 * @return Document object to rss
	 * @throws ParserConfigurationException
	 * @throws SAXException
	 * @throws IOException
	 */
	private Document createDocumentObjectFromInputStream(InputStream stream) throws ParserConfigurationException,SAXException,IOException{
		DocumentBuilderFactory dbfactory=DocumentBuilderFactory.newInstance();
		DocumentBuilder dbbuilder=dbfactory.newDocumentBuilder();
		Document doc=dbbuilder.parse(stream);
		return doc;
	}
	
	private String site;
}